<template>
  <div class="app-container">
    <el-button style="margin-bottom: 20px;" type="primary" @click="add(0)">添加</el-button>
    <el-button style="margin-bottom: 20px;" type="danger" @click="del()">批量删除</el-button>
    <el-form :inline="true" style="float:right;" class="demo-form-inline">
      <el-form-item label="关键词">
        <el-input v-model="keyWord.keyWord" placeholder="请输入昵称/账户名搜索" />
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="getList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableData.data"
      stripe
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        prop="id"
        label="ID"
      />
      <el-table-column
        label="展示图"
      >
        <template slot-scope="scope">
          <img height="100px" :src="baseURL+scope.row.img">
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
      />
      <el-table-column
        prop="subtitle"
        label="子标题"
      />

      <el-table-column
        label="最近登录时间"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.create_time">{{ timestampToTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
          <el-tag v-else type="info">隐藏</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="add(scope.row)">编辑</el-button>
          <el-button type="text" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="text-align:center;margin-top:20px"
      background
      layout="prev,pager,next,sizes,total,jumper"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="keyWord.pageCount"
      :total="total"
      :current-page="keyWord.page"
      @current-change="currentChange"
      @size-change="sizeChange"
    />

    <el-dialog
      title="分配节点权限"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <div>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="展示图">
            <el-upload
              :auto-upload="true"
              name="file"
              class="avatar-uploader"
              :action="getUploadUrl()"
              :headers="Headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.img" :src="baseURL+form.img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="子标题">
            <el-input v-model="form.subtitle" placeholder="请输入子标题" />
          </el-form-item>
          <el-form-item label="内容">
            <vue-egdit
              id="editor"
              ref="editor"
              :value="form.content"
              width="100%"
              :js-filter:="true"
              :hide-link-img="true"
              :upload-headers="Headers"
              :upload-img-url="getUploadUrl()"
              @load="insertImg"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="2">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="sub()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { ArticleGet, ArticleEdit, ArticleDel } from '@/api/article'
import { baseURL } from '@/utils/request'
import { getToken } from '@/utils/auth'
import vueEgdit from 'vue-wangeditor'
export default {
  name: 'User',
  components: {
    vueEgdit
  },
  data() {
    return {
      tableData: [],
      loading: true,
      dialogVisible: false,
      total: 0,
      keyWord: {
        page: 1,
        pageCount: 10,
        keyWord: ''
      },
      form: {
        id: '',
        title: '',
        subtitle: '',
        content: '',
        status: '',
        img: ''
      },
      oldForm: {
        id: '',
        title: '',
        subtitle: '',
        content: '',
        status: 1,
        img: ''
      },
      baseURL: baseURL,
      roleList: [],
      imageUrl: '',
      Headers: { __TOKEN__: getToken() }, // 上传文件头部header
      multipleSelection: [] // 表格多选
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 表格多选事件
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    // 富文本添加图片
    insertImg(originalName, resultText) {
      resultText = JSON.parse(resultText)
      if (resultText.code !== 200) {
        this.$message.error(resultText.err)
        return
      }
      this.$refs.editor.insertImg(baseURL + resultText.filePath)
    },
    // 获取上传地址
    getUploadUrl() {
      return baseURL + 'admin/Upload'
    },
    // 单图上传
    handleAvatarSuccess(res, file) {
      if (res.code !== 200) {
        this.$message.error(res.err)
        return
      }
      this.form.img = res.filePath
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 指定上传图片格式
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 8
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或者 png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 8MB!')
      }
      return isJPG && isLt2M
    },
    sizeChange(e) {
      this.keyWord.pageCount = e
      this.keyWord.page = 1
      this.loading = true
      this.getList()
    },
    currentChange(e) {
      this.keyWord.page = e
      this.loading = true
      this.getList()
    },
    async getList() {
      this.loading = true
      this.tableData = []
      ArticleGet(this.keyWord).then(response => {
        this.loading = false
        this.tableData = response.data || []
        this.total = response.data.total || 0
      }).catch(() => {
        this.loading = false
      })
    },
    timestampToTime(times) {
      var date = new Date(times * 1000) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      var D = date.getDate() + ' '
      var h = date.getHours() + ':'
      var m = date.getMinutes() + ':'
      var s = date.getSeconds()
      return Y + M + D + h + m + s
    },
    add(data) {
      this.dialogVisible = true
      if (data) {
        this.form = data
        this.$refs.editor.setHtml(data.content)
      } else {
        this.form = this.oldForm
        this.$refs.editor.clear()
      }
    },
    sub() {
      this.loading = true
      this.form.content = this.$refs.editor.getHtml()
      ArticleEdit(this.form).then(res => {
        this.dialogVisible = false
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.getList()
      }).catch(() => {
        this.loading = false
      })
    },
    del(id = '') {
      if (!id && this.multipleSelection.length == 0) {
        this.$message.error('没有选中相关内容')
        return
      }
      if (!id) {
        var idArr = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          idArr.push(this.multipleSelection[i].id)
        }
        id = idArr.join(',')
      }
      this.$confirm('删除后不可恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        ArticleDel({ id: id }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss">
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
